/**
 * 
 */
package common.liusany.admin.web.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailSendException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liusany.modules.orm.Page;
import com.liusany.modules.orm.PropertyFilter;
import common.liusany.admin.bean.Setting;
import common.liusany.admin.entity.account.Email;
import common.liusany.admin.service.account.EmailManager;
import common.liusany.admin.service.account.MimeMailService;
import common.liusany.admin.utils.CommonAttribute;
import common.liusany.admin.utils.SettingUtil;

/**
 * 处理邮件系统功能的 controller
 * @author liusany
 * 2012-4-7
 */
@Controller
@RequestMapping(value = "/admin/email")
public class EmailController extends BaseCopntroller {
	
	private static Logger logger = LoggerFactory.getLogger(EmailController.class);
	
	@Resource
	private EmailManager emailManager;
	@Resource
	private MimeMailService mimeMailService;
	@Resource
	private ThreadPoolTaskExecutor taskExecutor;
	
	/**
	 * 系统设置
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "tosetting")
	public String tosetting(Model model){
		model.addAttribute("setting", SettingUtil.getSetting());
		return "admin/emailSetting";
	}
	
	/**
	 * 导入邮箱
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toupload")
	public String toupload(Model model){
		return "admin/emailForm";
	}
	
	/**
	 * 邮箱列表
	 * @param model
	 * @param pager
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "list", "" })
	public String list(Model model,Page<Email> pager,HttpServletRequest request) {
		try {
			List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
			pager.setOrderBy("id");
			pager = emailManager.findByPage(pager, filters);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		model.addAttribute("pager", pager);
		return "admin/emailList";
	}
	
	/**
	 * 发送邮件
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "tosend")
	public String tosend(Model model){
		CommonAttribute.TEST_STATUS =true;
		model.addAttribute("teststatus", CommonAttribute.TEST_STATUS);
		return "admin/sendForm";
	}
	
	/**
	 * 查看任务
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "viewtask")
	public String viewTask(Model model){
		model.addAttribute("activeCount", taskExecutor.getActiveCount());
		return "admin/taskView";
	}
	
	
	/**
	 * ajax 发送邮件测试
	 * @param smtpFromMail
	 * @param smtpHost
	 * @param smtpPort
	 * @param smtpUsername
	 * @param smtpPassword
	 * @param smtpToMail
	 * @return
	 */
	@RequestMapping(value = "sendtest")
	@ResponseBody
	public Object ajaxSendSmtpTest(String smtpFromMail,String smtpHost,Integer smtpPort,
			String smtpUsername,String smtpPassword,String smtpToMail,String subject){
		try {
			mimeMailService.sendSmtpTestMail(smtpFromMail,smtpHost, smtpPort, smtpUsername, smtpPassword, smtpToMail,subject);
			CommonAttribute.TEST_STATUS = true;
		} catch (MailAuthenticationException e) {
			CommonAttribute.TEST_STATUS = false;
			return ajaxJsonErrorMessage("权限验证失败，请检查SMTP用户名、密码！");
		} catch (MailSendException e) {
			CommonAttribute.TEST_STATUS = false;
			return ajaxJsonErrorMessage("邮件发送失败，请检查发件人邮箱、SMTP服务器地址、端口！");
		} catch (Exception e) {
			e.printStackTrace();
			CommonAttribute.TEST_STATUS = false;
			return ajaxJsonErrorMessage("邮件发送失败！");
		}
		return ajaxJsonSuccessMessage("测试邮件发送成功，请查收邮件！");
		
		
	}
	
	/**
	 * 修改邮件设置
	 * @param setting
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updatesetting")
	public String updateSetting(Setting setting,Model model){
		Setting persistent = SettingUtil.getSetting();
		if(StringUtils.isEmpty(setting.getSmtpPassword())){
			setting.setSmtpPassword(persistent.getSmtpPassword());
		}
		SettingUtil.update(setting);
		setRedirectInfo("admin/email/tosetting", "系统设置成功", model);
		return SUCCESS;
	}
	
	/**
	 * 上传邮箱信息文件 并读取到数据中
	 * @param file
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "upload")
	@ResponseBody
	public Object upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,
			ModelMap model){
		HashMap<String,Object> hashmap = new HashMap<String,Object>();
		//保存
        try {
			Long start = System.currentTimeMillis();
	        String path = request.getSession().getServletContext().getRealPath("upload");
	        String fileName = file.getOriginalFilename();
	        File targetFile = new File(path, fileName);
	        if(!targetFile.exists()){
	            targetFile.mkdirs();
	        }
            file.transferTo(targetFile);
            //清理数据中的数据
            emailManager.deleteAll();
            int count = emailManager.fileToDb(targetFile);
            hashmap.put("status", "INSERT_FINISH");
            hashmap.put("count", count);
            hashmap.put("buildTime", Long.valueOf(System.currentTimeMillis() - start));
        } catch (Exception e) {
        	logger.error(e.getMessage());
        }
        return hashmap;
	}
	
	/**
	 * 执行发送邮件任务
	 * @param firstResult
	 * @param maxResults
	 * @return
	 */
	@RequestMapping(value = "send")
	public String send(@RequestParam("firstResult") Integer firstResult,@RequestParam("maxResults") Integer maxResults){
		
		CommonAttribute.TASK_EXES_STATUS = true;
		
		try {
			if (maxResults == null || maxResults < 0) {
				maxResults = 1000;
			}
			if (firstResult == null || firstResult < 0) {
				firstResult = 0;
			}
			List<Email> list = new ArrayList<Email>();
			
			list = emailManager.getEmailList(firstResult,maxResults);
			if (list != null && list.size() > 0)
			{
				for(Email email : list){
					emailManager.sendHtmlMail(email);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:/admin/email/viewtask";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
//	@RequestMapping(value = "send")
//	@ResponseBody
//	public Object send(@RequestParam("firstResult") Integer firstResult,@RequestParam("maxResults") Integer maxResults){
//		
//		logger.info("send run....."+(countt++)+"次数");
//		long l = System.currentTimeMillis();
//		
//		if (maxResults == null || maxResults < 0) {
//			maxResults = 100000;
//		}
//		if (firstResult == null || firstResult < 0) {
//			firstResult = 0;
//		}
//		List<Email> list = new ArrayList<Email>();
//		
//		list = emailManager.getEmailList(firstResult,maxResults);
//		if (list != null && list.size() > 0)
//		{
//			for(Email email : list){
//				emailManager.sendHtmlMail(email);
//			}
//			
//		}
//		if (list != null && list.size() == maxResults.intValue())
//		{
//			HashMap hashmap = new HashMap();
//			hashmap.put("status", "EMAIL_SENDING");
//			hashmap.put("firstResult", Integer.valueOf(firstResult.intValue() + list.size()));
//			hashmap.put("buildCount", maxResults);
//			hashmap.put("buildTime", Long.valueOf(System.currentTimeMillis() - l));
//			return hashmap;
//		} else
//		{
//			HashMap hashmap1 = new HashMap();
//			hashmap1.put("status", "PRODUCT_FINISH");
//			hashmap1.put("buildCount", Integer.valueOf(list.size()));
//			hashmap1.put("buildTime", Long.valueOf(System.currentTimeMillis() - l));
//			return hashmap1;
//		}
//	}
//	@RequestMapping(value = "destroy")
//	public String destroy(){
//		CommonAttribute.TASK_EXES_STATUS = false;
//	    logger.info("用户:"+SecurityUtils.getSubject().getPrincipal()+"  销毁线程池任务");
//		return "admin/taskView";
//	}
//	
//	@RequestMapping(value = "waittask")
//	public String waitTask(){
//		try {
//			taskExecutor.wait();
//			logger.info("用户:"+SecurityUtils.getSubject().getPrincipal()+"  暂停线程池任务");
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		return "admin/taskView";
//	}
	
	
}
